document.addEventListener('DOMContentLoaded', () => {
    const searchInput = document.getElementById('searchInput');
    const searchButton = document.getElementById('searchButton');
    const resultsDiv = document.getElementById('results');
    const loadingDiv = document.getElementById('loading');
    const gptAnswer = document.getElementById('gptAnswer');
    const qcResults = document.getElementById('qcResults');
    const esResults = document.getElementById('esResults');

    function createResultCard(result) {
        return `
            <div class="result-card">
                <p class="result-content">${result.content}</p>
                <p class="result-source">来源: ${result.source}</p>
            </div>
        `;
    }

    async function handleSearch() {
        const query = searchInput.value.trim();
        if (!query) return;

        resultsDiv.classList.add('hidden');
        loadingDiv.classList.remove('hidden');

        try {
            const response = await fetch('http://localhost:3000/api/query', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    query,
                    top_k: 3,
                    modes: ["q-c"]
                })
            });

            const data = await response.json();
            
            gptAnswer.textContent = data.gpt_answer;
            qcResults.innerHTML = data.qc_results.map(createResultCard).join('');
            esResults.innerHTML = data.es_results.map(createResultCard).join('');

            loadingDiv.classList.add('hidden');
            resultsDiv.classList.remove('hidden');
        } catch (error) {
            console.error('搜索失败:', error);
            loadingDiv.classList.add('hidden');
            alert('搜索失败，请稍后重试');
        }
    }

    searchButton.addEventListener('click', handleSearch);
    searchInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') handleSearch();
    });
});
